package account

import (
	"context"
	"fmt"
	"module_demo/user-service/api/internal/biz"
	"module_demo/user-service/model"
	"time"

	"module_demo/user-service/api/internal/svc"
	"module_demo/user-service/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	userModel := model.NewUserModel(l.svcCtx.Mysql)
	user, err := userModel.FindByUsernameAndPwd(l.ctx, req.Username, req.Password)
	if err != nil {
		l.Logger.Error("查询用户失败=", err)
		return nil, biz.DBError
	}
	if user == nil {
		l.Logger.Error("用户名或密码错误=", err)
		return nil, biz.NameOrPwdError
	}

	//从redis中获取token
	tokenCache, err := l.svcCtx.Redis.GetCtx(l.ctx, "token-"+fmt.Sprintf("%d", user.Id))
	if err == nil {
		if tokenCache != "" {
			l.Logger.Info(fmt.Sprintf("从redis中获取token成功，token=%s", tokenCache))
			return &types.LoginResp{
				Token: tokenCache,
			}, nil
		}
	}

	var secret = l.svcCtx.Config.Auth.AccessSecret
	var expire = l.svcCtx.Config.Auth.Expire
	token, err := biz.GetJwtToken(secret, time.Now().Unix(), expire, user.Id)
	if err != nil {
		l.Logger.Error("生成token失败=", err)
		return nil, biz.GenerateTokenError
	}
	//将token存入redis
	err = l.svcCtx.Redis.SetexCtx(l.ctx, "token-"+fmt.Sprintf("%d", user.Id), token, int(expire))
	if err != nil {
		l.Logger.Error("token存入redis失败", err)
	}
	return &types.LoginResp{
		Token: token,
	}, nil

}
